<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">收货地址</p>
      </div>
    </div>
    <div class="change-password">
      <Form @submit="onSubmit">
        <Field v-model="passwordForm.currentPassword" name="当前密码" label="当前密码" type="password" placeholder="请输入当前密码"
               :rules="[{ required: true, message: '请输入当前密码' }]" />
        <Field v-model="passwordForm.newPassword" name="新密码" label="新密码" type="password" placeholder="请输入新密码"
               :rules="[{ required: true, message: '请输入新密码' }]" />
        <div style="margin: 16px;">
          <Button color="#FA6408" round block type="info" native-type="submit" :disabled="confirm_disabled">确认修改</Button>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
import {Form, Field, Button, Toast, Icon} from 'vant';
import http from '@/plugins/http';

export default {
  name: "ChangePasswordView",
  components: {
    Icon,
    Field,
    Form,
    Button
  },
  data() {
    return {
      confirm_disabled: false,
      passwordForm: {
        currentPassword: '',
        newPassword: ''
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    onSubmit() {
      this.confirm_disabled = true;
      const username = JSON.parse(sessionStorage.getItem('username'));
      http({
        method: 'post',
        url: `/user/${username}/changePassword`,
        data: {
          currentPassword: this.passwordForm.currentPassword,
          newPassword: this.passwordForm.newPassword
        }
      })
          .then(res => {
            console.log('Response:', res);
            if (res.statusCode === "200") {
              Toast.success({
                message: '密码修改成功，请重新登录',
                duration: 1000
              });
              sessionStorage.clear(); // 清除 session
              setTimeout(() => {
                this.$router.push('/'); // 跳转到登录页面
              }, 1000);
            } else {
              Toast.fail({
                message: res.message,
                duration: 1000
              });
            }
            this.confirm_disabled = false;
          })
          .catch(error => {
            console.error('Error:', error);
            Toast.fail({
              message: '密码修改失败，请稍后再试',
              duration: 1000
            });
            this.confirm_disabled = false;
          });
    }
  }
}
</script>

<style scoped>
.change-password {
  padding: 16px;
}
.regulatory-page {
  background-color: #F6F7F9;
  height: 100vh;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.title {
  display: flex;
  align-items: center;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}
</style>
